package com.woniu.learnfile.controller;

import com.woniu.learnfile.entity.ErrorResult;
import com.woniu.learnfile.service.DownloadFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * created  by woniu201
 * created in 2018/3/16
 */
@RestController
public class DownloadFileController extends BaseController {

    @Autowired
    DownloadFileService downloadFileService;

    @RequestMapping(value="/test2/{fileName:.+}", method= RequestMethod.GET)
    public String downloadFile(@PathVariable String fileName, HttpServletResponse resp){

        System.out.println(fileName);

        OutputStream os = null;
        try {
            byte[] fileBytes = downloadFileService.downloadFileService(fileName);
            if (fileBytes == null){
                resp.setStatus(400);
                return "文件不存在";
            }

            //设置响应头
            resp.setHeader("content-type", "application/octet-stream");
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment;filename="+fileName);
            resp.setHeader("Content-Length", String.valueOf(fileBytes.length));
            os = resp.getOutputStream();
            os.write(fileBytes);
            os.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @RequestMapping(value="/aaa", method = RequestMethod.GET)
    public ResponseEntity<?> test(){
        return fail(new ErrorResult(400.1, "测试返回值"), HttpStatus.BAD_REQUEST);
    }
}
